//
//  ViewController.m
//  HeJuBao
//
//  Created by chris on 15/10/28.
//  Copyright (c) 2015年 Chris. All rights reserved.
//

#import "LogoViewController.h"
#import "IntroduceViewController.h"
#import "WebViewController.h"

#import "UIImageView+WebCache.h"
#import "NSDictionary+getValues.h"
#import "View+MASAdditions.h"

#import "HePreferrence.h"
#import "SessionMgr.h"
#import "HeConstants.h"
#import "Utils.h"
#import "AppDelegate.h"

#import "HTTPRequestManager.h"
#import "VersionInfo.h"
#import "FlashPicInfo.h"

@interface LogoViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *flashImageView;
@property (weak, nonatomic) IBOutlet UIImageView *logoImageView;

@property (nonatomic, assign) BOOL isNeedLoading;
@property (nonatomic, retain) VersionInfo * versionInfo;
@property (nonatomic, retain) FlashPicInfo * flashPicInfo;

@property (nonatomic, strong) NSString * strNewVersionUrl;

@end

@implementation LogoViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])
    {
        UIStoryboard* mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        self = [mainStoryboard instantiateViewControllerWithIdentifier:@"LogoViewController"];
    }
    
    return self;
}

//隐藏状态栏
- (BOOL)prefersStatusBarHidden{
    return YES;//隐藏为YES，显示为NO
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //下载闪屏
    [self requestFlashPic];
    
    //检查版本
    [self checkVersion];
    
    WS(ws);
    _imageBottom = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"flash_bottom"]];
    [self.view addSubview:_imageBottom];
    [_imageBottom mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(ws.view).offset(0);
        make.right.equalTo(ws.view).offset(0);
        make.bottom.equalTo(ws.view).offset(0);
        make.height.equalTo(@(108*height568));
    }];
}

//判断怎么跳转界面
-(void)whatGo{
    
    //BOOL isUpdataAPP = NO;
    
    /****  根据是否有闪屏 决定延时多少 ***/
    int delay = 1;
    if (self.hasFlashView)
    {
        delay = 3;
    }else{
        delay = 1;
    }
    
    if ([HePreferrence hasShowIntroducePage] == NO)            //全新用户才能看到引导页
    {
        [self performSelector:@selector(GoToIntroducePage) withObject:nil afterDelay:delay];
    }
    else
    {
        NSLog(@"tt");
        [self performSelector:@selector(GoToMainPage) withObject:nil afterDelay:delay];
    }
}

//去往主界面
-(void)GoToMainPage{
    
    //创建tab主controller
    WebViewController * controller = [[WebViewController alloc] initWithNibName:@"WebViewController" bundle:nil];
    [self.navigationController pushViewController:controller animated:YES];
}

//去往引导界面
IntroduceViewController *introduceViewController;
-(void)GoToIntroducePage{
    [self stopLoading];
    
    if (introduceViewController!=nil) {
        return;
    }
    
    BOOL isAnimated = YES;

    introduceViewController = [[IntroduceViewController alloc] init];
    [self.navigationController pushViewController:introduceViewController animated:isAnimated];
}

#pragma mark - 检查版本
-(void)checkVersion
{
    self.isNeedLoading = NO;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:10];
    
    [[HTTPRequestManager shareInstance] postRequestMethodWithURL:getVersion withParameters:dic andBtn:nil whenSuccess:^(HTTPRequestManager *manager, id model) {
        [self parseVersion:model];
        NSString *strVersionType = _versionInfo.strVersionType;
        NSString *strVersionMessage = _versionInfo.strVersionMessage;
        if ([strVersionType intValue] == 1)
        {
            [SessionMgr Instance].hasNewApp = YES;
            UIAlertView *av = [[UIAlertView alloc]initWithTitle:AlertTitle message:strVersionMessage delegate:self cancelButtonTitle:AlertUpdateButtonTitle otherButtonTitles:AlertCloseButtonTitle, nil];
            [av show];
        } else if ([strVersionType intValue] == 2)//强制更新
        {
            [SessionMgr Instance].hasNewApp = YES;
            UIAlertView *av = [[UIAlertView alloc]initWithTitle:AlertTitle message:strVersionMessage delegate:self cancelButtonTitle:AlertUpdateButtonTitle otherButtonTitles:Nil, nil];
            [av show];
        }
        else
        {
            [SessionMgr Instance].hasNewApp = NO;
            [self whatGo];
        }
        
    } RspCDFailed:^(HTTPRequestManager *manager, id model) {
        [self whatGo];
    } Faild:^(HTTPRequestManager *manager, NSError *error) {
        [self whatGo];
    }];
    
}

//解析版本检查数据
-(void)parseVersion:(NSDictionary *)dictJson{
    NSString* strVersionType = [dictJson objectForKey:@"versionType"];
    NSString *strVersionMessage =[dictJson objectForKey:@"versionMessage"];
    NSString *strVersionUrl =[dictJson objectForKey:@"versionUrl"];
    _strNewVersionUrl = [Utils isBlankString:strVersionUrl];
    
    _versionInfo = [[VersionInfo alloc]init];
    _versionInfo.strVersionUrl = [Utils isBlankString:strVersionUrl];
    _versionInfo.strVersionType = [Utils isBlankString:strVersionType];
    _versionInfo.strVersionMessage = [Utils isBlankString:strVersionMessage];
}

#pragma mark - 下载闪屏
-(void)requestFlashPic
{
    self.isNeedLoading = NO;
    
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]initWithCapacity:10];
    
    [[HTTPRequestManager shareInstance]postRequestMethodWithURL:getFlashPic withParameters:dic andBtn:nil whenSuccess:^(HTTPRequestManager *manager, id model) {
        
        NSString* flashPictureURL = [model objectForKey:@"indexUrl"];
        NSString *beginTime =[model objectForKey:@"beginTime"];
        NSString *endDate =[model objectForKey:@"endDate"];
        NSString *beginDate =[model objectForKey:@"beginDate"];
        NSString *endTime =[model objectForKey:@"endTime"];
        
        _flashPicInfo = [[FlashPicInfo alloc]init];
        _flashPicInfo.strBeginDate = [Utils isBlankString:beginDate];
        _flashPicInfo.strBeginTime = [Utils isBlankString:beginTime];
        _flashPicInfo.strEndDate = [Utils isBlankString:endDate];
        _flashPicInfo.strEndTime = [Utils isBlankString:endTime];
        _flashPicInfo.strIndexUrl = [Utils isBlankString:flashPictureURL];
        
        [self refreshView];    //更新闪屏
        NSLog(@"ccc");
    } RspCDFailed:^(HTTPRequestManager *manager, id model) {
        NSLog(@"闪屏响应失败");
    } Faild:^(HTTPRequestManager *manager, NSError *error) {
        NSLog(@"闪屏调用失败");
    }];
}

/*********刷新界面动作**********/
bool isHaveFlashView = YES;
-(void)refreshView{
    NSString* flashPictureURL = _flashPicInfo.strIndexUrl;
    if ([flashPictureURL length]>0){
        isHaveFlashView = YES;
        [HePreferrence setValue:flashPictureURL forKey:@"flashPictureURL"];
        NSURL *url = [NSURL URLWithString:flashPictureURL];
        
        [self.logoImageView sd_setImageWithURL:url];
        [UIView transitionWithView:self.logoImageView duration:0.5 options:UIViewAnimationOptionTransitionCrossDissolve animations:nil completion:nil];
    }
    [self.view bringSubviewToFront:self.logoImageView];
    //隐藏其他所有图片
    self.flashImageView.hidden = YES;
}

#pragma mark 版本检查更新代理
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    // 更新
    if (buttonIndex == 0){
        NSString* strVersionType = _versionInfo.strVersionType;
        if ([strVersionType intValue] == 1) {
            
        } else if ([strVersionType intValue] == 2)//强制更新
        {
            [self performSelector:@selector(exitApp) withObject:nil afterDelay:1];
        }
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_strNewVersionUrl]];
    }
    // 关闭
    else{
        [self whatGo];
    }

}

#pragma mark - 退出程序
-(void)exitApp {
    [((AppDelegate *)[UIApplication sharedApplication].delegate) exitApplication];
}

@end
